package cn.growthgate.fgo.web;

import java.util.List;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;

import cn.growthgate.fgo.common.Constants;
import cn.growthgate.fgo.common.base.BaseVo;
import cn.growthgate.fgo.entity.Image;
import cn.growthgate.fgo.entity.User;
import cn.growthgate.fgo.entity.enums.Role;
import cn.growthgate.fgo.service.IImageService;
import cn.growthgate.fgo.service.IUserRoleService;
import cn.growthgate.fgo.service.IUserService;
import cn.growthgate.fgo.util.AuthenticationUtils;
import cn.growthgate.fgo.util.CacheUtils;
import cn.growthgate.fgo.util.StringUtils;
import cn.growthgate.fgo.web.result.JsonResult;
import cn.growthgate.fgo.web.result.TableResult;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author GrowthGate
 * @since 2019-01-20
 */
@Controller
@RequestMapping("/user")
@RequiresRoles(value = {Constants.ROLE_ADMIN}, logical = Logical.OR)
public class UserController {

	@Autowired
	private IUserService userService;

	@Autowired
	private IUserRoleService userRoleService;

	@Autowired
	private IImageService imageService;

	@RequestMapping("/list")
	public String list() {
		return "user/list";
	}

	@ResponseBody
	@RequestMapping("/tableData")
	public TableResult<BaseVo<User>> tableData(User user, Integer current, Integer size) {
		Wrapper<User> wrapper = new EntityWrapper<>();

		if (StringUtils.isNotBlank(user.getUsername())) {
			wrapper.like("username", user.getUsername());
		}
		if (StringUtils.isNotBlank(user.getName())) {
			wrapper.like("name", user.getName());
		}
		if (user.getStatus() != null) {
			wrapper.eq("status", user.getStatus());
		}

		Page<User> page = userService.selectPage(current, size, wrapper);
		return new TableResult<BaseVo<User>>(userService.transformVo(page));
	}

	@RequestMapping("/form")
	public ModelAndView form(Long id) {
		User entity = userService.selectById(id);
		List<Role> userRoles = userRoleService.getRoles(id);

		return new ModelAndView("user/form").addObject("entity", entity).addObject("userRoles", userRoles);
	}

	@ResponseBody
	@RequestMapping("/save")
	public JsonResult save(@Validated(User.Create.class) User user, BindingResult bindingResult, Role[] roles) {
		if (bindingResult.hasErrors()) {
			return JsonResult.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
		}
		if (user.getId() == null) {
			// 添加用户
			if (StringUtils.isBlank(user.getUsername())) {
				return JsonResult.fail("用户名不能为空");
			}
			User existsUser = userService.getByUsername(user.getUsername());
			if (existsUser != null) {
				return JsonResult.fail("用户名已被使用");
			}
			existsUser = userService.getByName(user.getName());
			if (existsUser != null) {
				return JsonResult.fail("昵称已被使用");
			}
			// 默认密码
			user.setPassword("123456");
			if (!userService.create(user)) {
				return JsonResult.fail("添加用户失败");
			}
		} else {
			// 编辑用户
			User oUser = userService.selectById(user.getId());
			if (oUser == null) {
				return JsonResult.fail("用户不存在");
			}
			if (!oUser.getName().equals(user.getName())) {
				User existsUser = userService.getByName(user.getName());
				if (existsUser != null) {
					return JsonResult.fail("昵称已被使用");
				}
			}
			// 更改图片
			if (oUser.getAvatar() != null && !oUser.getAvatar().equals(user.getAvatar())) {
				imageService.deleteByEntity(oUser.getClass().getSimpleName(), oUser.getId());
				oUser.setAvatar(user.getAvatar());
			}
			oUser.setName(user.getName());
			oUser.setSex(user.getSex());
			oUser.setClient(user.getClient());
			oUser.setPyCode(user.getPyCode());
			oUser.setStatus(user.getStatus());
			if (!userService.updateAllColumnById(oUser)) {
				return JsonResult.fail("编辑用户失败");
			}
			user = oUser;
		}
		if (StringUtils.isNotBlank(user.getAvatar())) {
			Image image = imageService.getByUUID(user.getAvatar());
			image.setEntityId(user.getId());
			image.setEntityName(user.getClass().getSimpleName());
			imageService.updateById(image);
		}
		// 保存用户权限
		if (userRoleService.saveRoles(user.getId(), roles)) {
			// 权限有更改
			AuthenticationUtils.clearCachedAuthorizationInfo(user);
			// 清除菜单缓存
			CacheUtils.clear(Constants.CACHE_USER_MENUS);
		}
		return JsonResult.ok();
	}

	@ResponseBody
	@RequestMapping("/resetPassword")
	public JsonResult resetPassword(Long id) {
		User user = userService.selectById(id);
		if (user != null) {
			userService.setPassword(user, "123456");
			if (userService.updateById(user)) {
				return JsonResult.ok("重置密码成功");
			}
		}
		return JsonResult.fail("重置密码失败");
	}

}
